#include "serial.h"

Serial::Serial(QObject *parent)
    : QObject{parent}
{
    connect(m_serialPort,&QSerialPort::readyRead,this,&Serial::PortReceive);
}

/*String转十六进制，并根据指定长度自动生成字符串
 * "00 AA CC 00 00"
 */
QString StringToHex_pro(QString str, int length) {
    QString str_return;
    QString temp = QString("%1").arg(QString::number(str.toInt(), 16), length * 2,
                                     QLatin1Char('0'));

    // i--是因为低位在前，=0是为了最后一位
    for (int i = temp.length() / 2 - 1; i >= 0; i--) {
        str_return += temp.mid(i * 2, 2) + " ";
    }
    temp.clear();
    return str_return;
}

void Serial::PortOpen(QString portName,QSerialPort::BaudRate baudRate) {
    //初始化串口信息
    m_serialPort->setPortName(portName);
//    m_serialPort->setBaudRate(QSerialPort::Baud9600);
    m_serialPort->setBaudRate(baudRate);
    m_serialPort->setDataBits(QSerialPort::Data8);
    m_serialPort->setParity(QSerialPort::NoParity);   //设置奇偶校验位
    m_serialPort->setStopBits(QSerialPort::OneStop);  //设置停止位
    m_serialPort->setFlowControl(QSerialPort::NoFlowControl);
    qDebug() << "born:" << QThread::currentThread();
    if (m_serialPort->open(QIODevice::ReadWrite))  //打开串口
        isOpen = 1;
    else
        isOpen = 0;
}

void Serial::PortClose()
{
    m_serialPort->close();
    isOpen = 0;
}

void Serial::PortSend(QString lineStr)
{
    QString temp;
    QByteArray bytes;
    qDebug() << QThread::currentThread() << ":" << lineStr << "length:" << lineStr.length();
    for(int i = 0;i < (lineStr.length()+1)/3;i++)
    {
        temp.append(lineStr.mid(i*3,2));
    }//去掉语句中的空格
    bytes = QByteArray::fromHex(temp.toLatin1());//转成16进制发送
    m_serialPort->write(bytes);
    qDebug() << "Message:" << bytes;
}

void Serial::PortReceive()
{
    QByteArray recvByte;
    recvByte = m_serialPort->readAll();
    //qDebug() << "Serial received:" << recvByte;

    //数据处理模块
    dataProcess(recvByte);
    emit recvData(recvByte);
}

void Serial::dataProcess(QByteArray dataByte)
{
    //获取字节int xData = static_cast<unsigned char>(dataByte.at(0));
    short xData = static_cast<unsigned char>(dataByte.at(0)) << 8 | static_cast<unsigned char>(dataByte.at(1));
    double data = xData/100.0;
    qDebug()<< "xData:" << xData << "data:" << data;//这句话可以核对提取这些元素的功能效果
    emit dataUpdate(i,data);
    i++;
}

void Serial::test(int i,int data)
{
    emit dataUpdate(i,data);
}

Serial::~Serial()
{
    Serial::PortClose();
}
